package com.fulu.game.bi.advice;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fulu.game.bi.common.util.http.RequestUtils;
import com.fulu.game.bi.entity.po.auth.BiUser;
import com.fulu.game.bi.redis.service.auth.BiUserService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Aspect
@Component
@Slf4j
public class LogAspect {
    @Autowired
    private BiUserService userService;

    @Pointcut("execution(public * com.fulu.game.bi.controller..*.*(..))")
    public void webLog() {//NOPMD
    }

    /**
     * 接收请求，并记录数据
     *
     * @param joinPoint
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        BiUser admin = userService.getCurrentUser();
        Object[] args = joinPoint.getArgs();
        List<Object> arguments = Arrays.asList(args).stream().filter(map -> !(map instanceof ServletRequest || map instanceof ServletResponse || map instanceof MultipartFile)).collect(Collectors.toList());
        String paramter = null;
        try {
            paramter = JSONObject.toJSONString(arguments);
        } catch (Exception e) {
            log.error("BI ACCESS LOG ", e);
        }
        log.info("BI ACCESS LOG URI: {},IP: {} ,ARGS: {},TIME: {},ADMIN: {}",
                request.getRequestURI(), RequestUtils.getIpAdrress(request), paramter, DateUtil.formatDateTime(new Date()), JSON.toJSON(admin));
    }


}